package cn.wolfcode.crm.web.controller;


import cn.wolfcode.crm.query.ChartQueryObject;
import cn.wolfcode.crm.service.IChartService;
import cn.wolfcode.crm.util.JSONUtil;
import cn.wolfcode.crm.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("chart")
@Controller
public class ChartController {
    @Autowired
    private IChartService chartService;

    @RequestMapping("list")
    public String list(Model model,@ModelAttribute("qo") ChartQueryObject qo) {
        model.addAttribute("list", chartService.queryForChart(qo));
        return "chart/list";
    }
    @RequestMapping("bar")
    public String bar(Model model,@ModelAttribute("qo") ChartQueryObject qo) {
        List<Map<String, Object>> list = chartService.queryForChart(qo);
        List<Object> x = new ArrayList<>();
        List<Object> y = new ArrayList<>();
        for (Map<String, Object> map : list) {
            x.add(map.get("groupType"));
            y.add(map.get("totalNumber"));
        }
        model.addAttribute("groupType", MessageUtil.changMsg(qo));
        model.addAttribute("x", JSONUtil.toJSONString(x));
        model.addAttribute("y", JSONUtil.toJSONString(y));
        return "chart/bar";
    }

    @RequestMapping("pie")
    public String pie(Model model,@ModelAttribute("qo") ChartQueryObject qo) {
        List<Map<String, Object>> list = chartService.queryForChart(qo);
        List<Object> x = new ArrayList<>();
        List<Map<Object,Object>> datas = new ArrayList<>();
        for (Map<String, Object> map : list) {
            x.add(map.get("groupType"));
            // datas中每个对象都是一个map
            // map中的key是name,value,value是groupType,totalNumber
            Map<Object,Object> data = new HashMap<>();
            data.put("name",map.get("groupType"));
            data.put("value",map.get("totalNumber"));
            datas.add(data);
        }
        model.addAttribute("groupType", MessageUtil.changMsg(qo));
        model.addAttribute("x", JSONUtil.toJSONString(x));
        model.addAttribute("datas", JSONUtil.toJSONString(datas));
        return "chart/pie";
    }
}
